package service

import (
	"document_manager/global"
	"document_manager/model"
	"errors"
	"fmt"
	"os"
	"path/filepath"
	"runtime"
)

// GetDirFiles 获取目录文件
func GetDirFiles(path string, IsWithChild bool) (interface{}, error) {
	var lstFile []model.FileInfo
	if IsWithChild {
		//递归
		err := filepath.Walk(getLocalDir(path), func(path string, info os.FileInfo, err error) error {
			lstFile = append(lstFile, model.FileInfo{FileName: info.Name(), Path: path, IsDir: info.IsDir(), IsFile: !info.IsDir(), Size: info.Size()})
			return nil
		})
		if err != nil {
			return nil, err
		}
	} else {
		//仅当前文件夹，不递归
		fileInfoList, err := os.ReadDir(getLocalDir(path))
		if err != nil {
			return nil, err
		}
		for _, dirEntry := range fileInfoList {
			info, err := dirEntry.Info()
			if err != nil {
				continue
			}
			//filePath := strings.Replace(path, global.ROOT_DIR, "", 1) //替换真实路径
			lstFile = append(lstFile, model.FileInfo{FileName: info.Name(), Path: path, IsDir: info.IsDir(), IsFile: !info.IsDir(), Size: info.Size()})
		}
	}
	return lstFile, nil
}

func NewFile(path string) (bool, error) {
	path = global.ROOT_DIR + path
	if PathExists(path) {
		return false, errors.New("文件已存在")
	}
	file, err := os.Create(path)
	if err != nil {
		fmt.Println("writer", err)
		return false, err
	}
	defer file.Close()
	return true, nil
}

// PathExists 判断文件夹是否存在
func PathExists(path string) bool {
	_, err := os.Stat(getLocalDir(path))
	if err == nil {
		return true
	}
	if os.IsNotExist(err) {
		return false
	}
	return false
}

// WriteTextFile 写到文件，若之前存在则直接替换
func WriteTextFile(path string, content string) (bool, error) {
	byteContent := []byte(content)
	//将指定内容写入到文件中
	err := os.WriteFile(getLocalDir(path), byteContent, 7777)
	if err != nil {
		return false, err
	}
	return true, nil
}

func DeleteFile(path string) (bool, error) {
	err := os.Remove(getLocalDir(path))
	if err != nil {
		return false, err
	}
	return true, nil
}

// 获取本地真实路径
func getLocalDir(path string) string {
	if runtime.GOOS == "Windows" {
		rootDir, _ := os.Getwd() //默认是运行目录
		return rootDir + path

	} else {
		return global.ROOT_DIR + path
	}
}
